<!--
 * @description  : 派单处理
 * @descriptionDetail : 派单处理
 * @author       : bln
 * @create       : 2024-05-15 00:00:00
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
      <view class="nav-right-icon">
				<u-icon color="#fff" name="plus" size="38" @click="isOpen = true" />
			</view>
    </theme-navbar>
    <!-- #endif -->
    <!-- #ifdef H5-WECHAT || H5-EMP -->
		 <fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="assign-task-lay" :style="{'top': isHideNav ? 0 : '44px'}">
      <view class="assign-task-warn">
        <span class="warn">派单提醒！</span> 您有{{ dataSource.length || 0 }}个派单待执行，请结合派单任务的风险等级、紧急程度、派单时效等，合理安排工作，把派单纳入到日计划里，及时检查！
      </view>
      <view class="tab-lay">
        <u-tabs :is-scroll="false" :list="tabList" :current="currentTab" @change="tabChange"></u-tabs>
      </view>
    </view>
    <view class="content u-page">
      <me-table :i="0" :top="108" :index="0" :load-data="loadData" :init-load="false" ref="mescrollItem0">
        <view slot-scope="d" class="list-lay">
          <view class="u-flex" @tap="handlerSelectItem(d.data)">
            <view class="u-p-r-10 u-p-b-10">
              <view class="circle" :style="{ backgroundColor: urgentColors[d.data.urgentLevel] }">{{ d.data.urgentLevelName }}</view>
            </view>
            <view class="u-flex-1">
              <view class="u-p-t-10 u-p-b-10">
                <text class="title">{{ d.data.companyName }}-{{ d.data.licNo }}</text>
              </view>
              <view class="u-p-t-10 u-p-b-10">
                <u-tag v-if="d.data.riskLevelName" class="u-m-r-10" mode="plain" :text="d.data.riskLevelName" :border-color="riskLevelColors[d.data.riskLevelHandle] || ''" :color="riskLevelColors[d.data.riskLevelHandle] || ''" />
                <u-tag v-if="d.data.controlPlanName" class="u-m-r-10" mode="plain" :text="d.data.controlPlanName" :border-color="controlPlanColors[d.data.controlPlan] || ''" :color="controlPlanColors[d.data.controlPlan] || ''" />
                <u-tag v-if="d.data.assignTaskTypeName" mode="plain" :text="d.data.assignTaskTypeName" :border-color="taskTypeColors[d.data.assignTaskType] || ''" :color="taskTypeColors[d.data.assignTaskType] || ''"  />
              </view>
              <view class="u-p-t-10 u-p-b-10">
                <text>派单人：{{ d.data.creator }}</text>
              </view>
              <view class="u-p-t-10 u-p-b-10">
                <text>派单时间：{{ d.data.assignTimeBegin }}</text>
              </view>
              <view class="u-p-t-10 u-p-b-10">
                <text>任务时效：{{ d.data.assignTimeBegin }}~{{ d.data.assignTimeEnd }}</text>
              </view>
            </view>
            <view class="right-tag">
              <u-tag mode="dark" shape="circle" :bg-color="statusColors[d.data.assignTaskStatus] || {}" :text="d.data.assignTaskStatusName" />
              <u-icon v-if="selectedUids.includes(d.data.taskUuid)" name="checkbox-mark" :color="$theme.u_type_primary" size="36" style="margin-left: 5px;" />
            </view>
          </view>
        </view>
      </me-table>
    </view>
    <u-popup mode="bottom" height="30%" width="100%" v-model="showMore">
			<view class="title-content">
				<u-form :model="planForm" :rules="rules" :errorType="errorType" style="padding: 15px;" ref="planForm">
					<u-form-item left-icon="calendar" required label="计划日期" prop="planDate" :label-width="180" right-icon="arrow-right">
            <u-input input-align="right" :custom-style="valueStyle" placeholder="请选择检查日期" :disabled="true" v-model="planForm.planDate" @tap="!isDisabled && (dateShow = true)" />
          </u-form-item>
          <u-form-item v-if="showChecker" left-icon="man-add" required label="执行人" prop="checkers" :label-width="180" right-icon="arrow-right">
            <u-input style="flex: 1;" :needValid="true" input-align="right" :custom-style="valueStyle" placeholder="请选择执行人" :disabled="true" v-model="planForm.checkers" @tap="personShow = true" />
          </u-form-item>
				</u-form>
				<view class="submit-btns btn-other-cls" style="margin-left:-30rpx">
					<u-button plain class="del" type="primary" @click="showMore = false">取消</u-button>
					<u-button class="mit" type="primary" @click="addDayPlan">确定</u-button>
				</view>
			</view>
		</u-popup>
    <u-action-sheet :list="addBtnsList" v-model="isOpen" @click="handlerDropMenu"></u-action-sheet>
    <!-- 计划日期 -->
    <u-calendar :min-date="getMinDate()" mode="date" max-date="9999-12-31" v-model="dateShow" @change="calendarChange"></u-calendar>
    <!-- 执行人 -->
    <u-popup mode="bottom" border-radius="14" height="80%" v-model="personShow">
      <multi-select :leftBtnOpt="leftBtnOpt" :options="personOptions" @select="handlerSelectPersons"></multi-select>
    </u-popup>
    <!-- 执行人选择更多 -->
    <u-popup mode="bottom" height="80%" v-model="orgPersonSelectShow">
      <org-person-select treeType="zm-user" modelType="market" @choose="handlerChoosePerson"></org-person-select>
    </u-popup>
    <!--是否创建日计划-->
    <u-modal title="提示" :show-cancel-button="true" cancel-text="取消" v-model="showCreate" @confirm="createPlan" content="没有查询到对应的日计划，是否创建?"/>
  </view>
</template>

<script>
import meTable from '@/components/me-table.vue'
import multiSelect from '@/components/multi-select.vue'
import checkService from '@/service/check/check.service'
import orgPersonSelect from '@/components/org-person-select.vue'
import MescrollMoreMixin from '@/components/mescroll-uni/mixins/mescroll-more.js'

export default{
  components: { meTable, multiSelect, orgPersonSelect },
	mixins: [MescrollMoreMixin],
  data(){
    return {
      isOpen:false,
      showMore: false,
      dateShow: false,
      personShow: false,
      showChecker: false,
      isDisabled: false,
      showCreate: false,
      orgPersonSelectShow:false,
      currentTab: 0,
      dayUuid: '',
      dataSource: [],
      selectedUids: [], // 选中项的id
			selectedItems: [], // 选中项
      personOptions: [], // 执行人
      leftBtnOpt:{
        isBack: true,
        backText: '更多选择',
        backIconName: 'man-add',
        backFun: () => {},
      },
      addBtnsList: [{
          text: '纳入日计划',
          color: '#007aff',
        }
			],
      urgentColors: {
        '01': '#AC0000',
        '02': '#EC7C37',
        '03': '#0079F2',
        '04': '#20AB5C'
      },
      statusColors: {
        '01': '#FF9E2C',
        '02': '#20AB5C',
        '03': '#AC0000',
        '04': '#717579'
      },
      riskLevelColors: {
        '01': '#AC0000',
        '02': '#EC7C37',
        '03': '#0079F2'
      },
      controlPlanColors: {
        '01': '#AC0000',
        '02': '#EC7C37'
      },
      taskTypeColors: {
        '01': '#AC0000',
        '02': '#EC7C37',
        '03': '#0079F2',
        '04': '#20AB5C'
      },
      tabList: [
        { name: '待检查' },
        { name: '全部' }
      ],
      valueStyle: {
        marginRight: '5px',
      },
      planForm: {
        planDate: '',
        checkers: ''
      },
      rules: {
        planDate: [
          {
            required: true,
            message: '请选择计划日期',
            trigger: ['change','blur']
          }
        ],
        checkers: [
          {
            message: '请选择执行人',
            trigger: ['change','blur',],
            validator: (rule, value, callback) => {
              return !this.$u.test.isEmpty(value)
            }
          }
        ]
      },
      fContent: [{
        active: false,
        text: '纳入日计划',
        iconPath: require('@/static/add.png'),
        selectedIconPath: require('@/static/add.png')        
      }],
      errorType: ['border-bottom', 'message']
    }
  },
  mounted() {
    this.leftBtnOpt.backFun = (pItems) => {
      this.personShow = false
      this.selectPersons = pItems
      this.orgPersonSelectShow = true
    }
  },
  watch: {
    showMore(val) {
      this.$nextTick(() => {
        val && this.$refs.planForm.setRules(this.rules)
      })
    }
  },
  methods:{
    // 加载列表数据
    loadData(pager) {
      return checkService.getMsgPageList({
        page: pager.num,
        limit: pager.size,
        taskStatus: this.currentTab === 0 ? '01' : '',
      }).then(res => {
        if (res.success) {
          this.dataSource = res.data
        }
        return res
      })
    },
    setRightBtns() {
      this.$deviceApi.setRight('纳入日计划', () => {
        this.handlerDropMenu()
        this.setRightBtns()
      }, true, true)
    },
    fabtrigger(btn) {
      if (btn.index == 0) {
        this.handlerDropMenu()
      }
    },
    // 列表tab切换
    tabChange(n) {
      this.currentTab = n
      this.getMescroll(0).triggerDownScroll()
    },
    // 选中项
    handlerSelectItem(item) {
      if (this.selectedUids.includes(item.taskUuid)) {
        this.selectedItems = this.selectedItems.filter(it => it.taskUuid != item.taskUuid)
      } else {
        this.selectedItems.push(item)
      }
      this.selectedUids = []
      this.selectedItems.forEach(it => this.selectedUids.push(it.taskUuid))
    },
    // 导航栏菜单
    handlerDropMenu(i) {
      this.isOpen = false
      if (i == 0) {
        if(this.selectedItems.length < 1) {
          return this.$u.toast('请先勾选派单任务！')
        }
        this.showMore = true
      }
    },
    // 日期限制
    getMinDate(){
      return this.$u.timeFormat(Date.now())
    },
    // 日历选择时调用
    calendarChange(d){
      this.planForm.planDate = d.result
      this.showMore = false
      this.getDayPlanExist()
    },
    // 执行人
    handlerSelectPersons(pItems) {
      this.personShow = false
      if((pItems || []).length <= 1){
        this.$u.toast('至少选择两个执行人')
        return
      }
      this.selectPersons = pItems
      this.planForm.checkers = this.selectPersons.map(item => item.name).join(',')
    },
    // 选择执行人-更多
    handlerChoosePerson(psrList){
      this.orgPersonSelectShow = false
      psrList = psrList.filter(itm => {
        for (let i = 0; i < this.selectPersons.length; i++) {
          if(this.selectPersons[i].personUuid == itm.id){
            return false
          }
        }
        return true
      })
      const newList = psrList.map(item => {
        return {
          personUuid: item.id,
          personName: item.name
        }
      })
      this.selectPersons = [...this.selectPersons, ...newList]
      if(this.selectPersons.length <= 1){
        return this.$u.toast('至少选择两个执行人')
      }
      this.planForm.checkers =  this.selectPersons.map(item => item.personName).join(',')
    },
    // 创建日计划
    createPlan() {
      this.showMore = true
      this.showChecker = true
    },
    // 纳入日计划
    addDayPlan() {
       this.$refs.planForm.validate(valid => {
        if (valid) {
          this.$u.loading('加载中...')
          checkService.addDayPlan({
            dayUuid: this.dayUuid,
            executorVOList: this.selectPersons,
            planDate: this.planForm.planDate,
            taskUuidList: this.selectedUids || [],
          }).then(dr => {
            if (dr.success) {
              this.$u.toast('添加成功！')
              this.selectedUids = []
              this.selectedItems = []
              this.getMescroll(0).triggerDownScroll()
            }
            this.showMore = false
            this.$u.hideLoading()
          }).catch((er) => {
            this.$u.hideLoading()
            this.$u.toast(er)
          })
        }
      })
    },
    // 查询当前登录人指定日期的重点检查计划
    getDayPlanExist() {
      this.$u.loading('加载中...')
      checkService.getDayPlanExist({ planDate: this.planForm.planDate }).then(dr => {
        this.$u.hideLoading()
        if (dr.success) {
          // code||01：没有日计划；02：有日计划，但可以添加到日计划里;03:不允许创建日计划
          const { code, dayUuid } = dr.bean
          this.dayUuid = dayUuid
          this.isDisabled = code === '01'
          if(code === '01') {
            this.showCreate = true
            this.planExecutorList()
          } else if(code === '02') {
            this.addDayPlan()
          } else {
            this.$u.toast('该日期的日计划已完成或者已终止，不能纳入派单，请检查！')
          }
        }
      }).catch((er) => {
        this.$u.hideLoading()
        this.$u.toast(er)
      })
    },
    // 查询执行人
    planExecutorList(){
      this.$u.loading("加载中...");
      checkService.findDayPlanExecutorList({ planDate:this.planForm.planDate, dayPlanType: '01' }).then(dr => {
        this.$u.hideLoading()
        if (dr.success) {
          let ps = dr.data
          ps.map(p => {
            p.uid = p.personUuid
            p.name = p.personName
            p.exts = [p.inspectionCertNo, p.mainJobName]
          })
          this.$nextTick(() => this.personOptions = ps)
        }
      }).catch((err) => {
        this.$u.toast(err)
        this.$u.hideLoading()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.content {
  margin-top: 65px;
  background-color: #f3f4f5;
}
.assign-task-lay {
  position: fixed;
  // #ifndef H5-DINGDING
  top: 44px;
  // #endif
  // #ifdef H5-DINGDING
  top: 0px;
  // #endif
  z-index: 999;
  width: 100%;
  overflow: hidden;
  background-color: #ffffff;
  border-bottom: 1px solid $u-border-color;
}
.assign-task-warn {
  padding: $cm-search-padding-row $cm-search-padding-column;
}
.list-lay {
  margin:20rpx;
  padding: 20rpx 12rpx;
  border-radius:15px;
  background-color: #FFF;
}
.title {
  font-size: 30rpx;
  font-weight: 700;
}
.warn {
  color: red;
  font-size: 16px;
  font-weight: 700;
}
.circle {
  width: 90rpx;
  height: 90rpx;
  color: #fff;
  border-radius: 50%;
  padding: 14px 0px;
  text-align: center;
  font-size: 12px;
}
.u-size-default {
  padding: 12rpx 16rpx;
}
</style>
